const { query, transaction } = require('../config/database');

class Friend {
  /**
   * 获取用户的好友列表
   * @param {string} userId - 用户ID
   * @returns {Array} 好友列表
   */
  static async getFriendsList(userId) {
    try {
      const sql = `
        SELECT 
          f.friend_id as userId,
          u.email,
          u.nick_name as nickName,
          u.avatar,
          u.status,
          f.created_at as friendSince
        FROM friendships f
        LEFT JOIN users u ON f.friend_id = u.user_id
        WHERE f.user_id = ? AND f.status = 1
        ORDER BY u.nick_name ASC
      `;
      
      const friends = await query(sql, [userId]);
      return friends;
    } catch (error) {
      console.error('获取好友列表失败:', error);
      throw new Error('获取好友列表失败');
    }
  }

  /**
   * 检查两个用户是否已经是好友
   * @param {string} userId - 用户ID
   * @param {string} friendId - 好友ID
   * @returns {boolean} 是否为好友关系
   */
  static async isFriend(userId, friendId) {
    try {
      const sql = `
        SELECT COUNT(*) as count
        FROM friendships 
        WHERE user_id = ? AND friend_id = ? AND status = 1
      `;
      
      const result = await query(sql, [userId, friendId]);
      return result[0].count > 0;
    } catch (error) {
      console.error('检查好友关系失败:', error);
      throw new Error('检查好友关系失败');
    }
  }

  /**
   * 添加好友（双向关系）
   * @param {string} userId - 用户ID
   * @param {string} friendId - 好友ID
   * @returns {Object} 操作结果
   */
  static async addFriend(userId, friendId) {
    try {
      // 检查是否为同一个用户
      if (userId === friendId) {
        throw new Error('不能添加自己为好友');
      }

      // 检查是否已经是好友
      const isAlreadyFriend = await this.isFriend(userId, friendId);
      if (isAlreadyFriend) {
        throw new Error('已经是好友关系');
      }

      // 使用事务添加双向好友关系
      await transaction(async (connection) => {
        const addFriendSql = `
          INSERT INTO friendships (user_id, friend_id, status) 
          VALUES (?, ?, 1)
        `;
        
        // 添加双向关系
        await connection.execute(addFriendSql, [userId, friendId]);
        await connection.execute(addFriendSql, [friendId, userId]);
      });

      return { success: true, message: '添加好友成功' };
    } catch (error) {
      console.error('添加好友失败:', error);
      throw error;
    }
  }

  /**
   * 删除好友（双向删除）
   * @param {string} userId - 用户ID
   * @param {string} friendId - 好友ID
   * @returns {Object} 操作结果
   */
  static async removeFriend(userId, friendId) {
    try {
      // 检查是否为好友关系
      const isCurrentlyFriend = await this.isFriend(userId, friendId);
      if (!isCurrentlyFriend) {
        throw new Error('不是好友关系');
      }

      // 使用事务删除双向好友关系（软删除）
      await transaction(async (connection) => {
        const removeFriendSql = `
          UPDATE friendships 
          SET status = 0, updated_at = CURRENT_TIMESTAMP 
          WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)
        `;
        
        await connection.execute(removeFriendSql, [userId, friendId, friendId, userId]);
      });

      return { success: true, message: '删除好友成功' };
    } catch (error) {
      console.error('删除好友失败:', error);
      throw error;
    }
  }

  /**
   * 根据邮箱搜索用户（用于添加好友）
   * @param {string} email - 邮箱地址
   * @param {string} currentUserId - 当前用户ID（排除自己）
   * @returns {Object|null} 用户信息
   */
  static async searchUserByEmail(email, currentUserId) {
    try {
      const sql = `
        SELECT 
          user_id as userId,
          email,
          nick_name as nickName,
          avatar,
          status
        FROM users 
        WHERE email = ? AND user_id != ?
      `;
      
      const users = await query(sql, [email, currentUserId]);
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('搜索用户失败:', error);
      throw new Error('搜索用户失败');
    }
  }

  /**
   * 发送好友申请
   * @param {string} fromUserId - 申请人ID
   * @param {string} toUserId - 被申请人ID
   * @param {string} message - 申请消息
   * @returns {Object} 操作结果
   */
  static async sendFriendRequest(fromUserId, toUserId, message = '') {
    try {
      // 检查是否为同一个用户
      if (fromUserId === toUserId) {
        throw new Error('不能向自己发送好友申请');
      }

      // 检查是否已经是好友
      const isAlreadyFriend = await this.isFriend(fromUserId, toUserId);
      if (isAlreadyFriend) {
        throw new Error('已经是好友关系');
      }

      // 检查是否已有待处理的申请
      const existingRequestSql = `
        SELECT COUNT(*) as count
        FROM friend_requests 
        WHERE from_user_id = ? AND to_user_id = ? AND status = 0
      `;
      
      const existingResult = await query(existingRequestSql, [fromUserId, toUserId]);
      if (existingResult[0].count > 0) {
        throw new Error('已有待处理的好友申请');
      }

      // 插入好友申请
      const insertSql = `
        INSERT INTO friend_requests (from_user_id, to_user_id, message, status)
        VALUES (?, ?, ?, 0)
      `;
      
      await query(insertSql, [fromUserId, toUserId, message]);
      return { success: true, message: '好友申请发送成功' };
    } catch (error) {
      console.error('发送好友申请失败:', error);
      throw error;
    }
  }

  /**
   * 获取收到的好友申请列表
   * @param {string} userId - 用户ID
   * @returns {Array} 好友申请列表
   */
  static async getReceivedRequests(userId) {
    try {
      const sql = `
        SELECT 
          fr.id,
          fr.from_user_id as fromUserId,
          u.email as fromUserEmail,
          u.nick_name as fromUserNickName,
          u.avatar as fromUserAvatar,
          fr.message,
          fr.created_at as requestTime
        FROM friend_requests fr
        LEFT JOIN users u ON fr.from_user_id = u.user_id
        WHERE fr.to_user_id = ? AND fr.status = 0
        ORDER BY fr.created_at DESC
      `;
      
      const requests = await query(sql, [userId]);
      return requests;
    } catch (error) {
      console.error('获取好友申请失败:', error);
      throw new Error('获取好友申请失败');
    }
  }

  /**
   * 处理好友申请（同意/拒绝）
   * @param {number} requestId - 申请ID
   * @param {string} userId - 当前用户ID
   * @param {number} action - 操作：1-同意，2-拒绝
   * @returns {Object} 操作结果
   */
  static async handleFriendRequest(requestId, userId, action) {
    try {
      // 验证申请是否存在且属于当前用户
      const checkSql = `
        SELECT from_user_id, to_user_id, status
        FROM friend_requests 
        WHERE id = ? AND to_user_id = ?
      `;
      
      const requestResult = await query(checkSql, [requestId, userId]);
      if (requestResult.length === 0) {
        throw new Error('好友申请不存在');
      }

      const request = requestResult[0];
      if (request.status !== 0) {
        throw new Error('该申请已被处理');
      }

      await transaction(async (connection) => {
        // 更新申请状态
        const updateRequestSql = `
          UPDATE friend_requests 
          SET status = ?, processed_at = CURRENT_TIMESTAMP 
          WHERE id = ?
        `;
        
        await connection.execute(updateRequestSql, [action, requestId]);

        // 如果同意申请，添加好友关系
        if (action === 1) {
          const addFriendSql = `
            INSERT INTO friendships (user_id, friend_id, status) 
            VALUES (?, ?, 1)
          `;
          
          // 添加双向关系
          await connection.execute(addFriendSql, [request.from_user_id, request.to_user_id]);
          await connection.execute(addFriendSql, [request.to_user_id, request.from_user_id]);
        }
      });

      const actionText = action === 1 ? '同意' : '拒绝';
      return { success: true, message: `${actionText}好友申请成功` };
    } catch (error) {
      console.error('处理好友申请失败:', error);
      throw error;
    }
  }
}

module.exports = Friend;